/**
 * 
 */
package fhq.hcmute.edu.vn.activities;

import java.io.ObjectOutputStream;
import java.security.PublicKey;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import fhq.hcmute.edu.vn.network.ComputerInfos;
import fhq.hcmute.edu.vn.network.Network;
import fhq.hcmute.edu.vn.network.PhoneInfos;
import fhq.hcmute.edu.vn.security.KeyManagement;
import fhq.hcmute.edu.vn.util.BundleUtil;
import fhq.hcmute.edu.vn.util.ProjectUtil;
import fhq.hcmute.edu.vn.util.TAG;

/**
 * @author Hien Nguyen Nov 20, 2012
 */
public class ConnectionHandler extends Handler {
	public static final int SECRECT_KEY = 0;
	public static final int HOSTNAME = 1;
	public static final int IP_ADDRESS = 2;
	public static final int PORT = 3;
	public static final int PASSWORD = 4;
	private Activity activity;
	private static String deviceName;
	private static String deviceModelNumber;
	private static String phoneIMEI;
	private static Network network;

	private static ConnectionHandler instance = null;

	public static ConnectionHandler getInstance(Activity activity) {

		if (instance == null) {
			instance = new ConnectionHandler(activity);
		}
		instance.activity = activity;
		return instance;
	}

	private ConnectionHandler(Activity activity) {
		TelephonyManager telephonyManager =
				(TelephonyManager) activity
						.getSystemService(Context.TELEPHONY_SERVICE);
		phoneIMEI = telephonyManager.getDeviceId();
		deviceModelNumber = Build.MODEL;
		deviceName = Build.MANUFACTURER + " " + android.os.Build.PRODUCT;
		network = Network.getInstance();
		network.setActivity(activity);
	}

	@Override
	public void handleMessage(Message msg) {
		super.handleMessage(msg);
		Bundle data = msg.getData();
		Log.v(TAG.NAME, "1");
		switch (msg.what) {
		case ProjectUtil.BARCODE_SCAN_RESULT:
			handleBarcodeScan(data);
			break;
		case ProjectUtil.AUTHENTICATION:
			handleAuthentication(data);
			break;
		case ProjectUtil.AUTHENTICATION_REMEMBER:
			try {
				handleAuthenticationRemember(data);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
	}

	private void handleAuthentication(final Bundle data) {
		boolean isSuccess = data.getBoolean(BundleUtil.AUTHENTICATION_KEY);
		if (isSuccess) {
			Intent intent =
					new Intent(activity.getApplicationContext(),
							MainFunctions.class);
			activity.startActivity(intent);
			activity.finish();
		} else {
			Toast.makeText(activity,
					activity.getString(R.string.Toast_Connect_Failure),
					Toast.LENGTH_SHORT).show();
		}
	}

	private void handleAuthenticationRemember(final Bundle data)
			throws Exception {
		boolean isSuccess = data.getBoolean(BundleUtil.AUTHENTICATION_KEY);
		PublicKey publicKey = (PublicKey) data
				.getSerializable(BundleUtil.AUTHENTICATION_PUBLIC_KEY);
		if (isSuccess) {
			ObjectOutputStream oout =
					new ObjectOutputStream(activity.openFileOutput(
							"public.key", Context.MODE_PRIVATE));
			KeyManagement.saveKey(oout, publicKey);
			Intent intent =
					new Intent(activity.getApplicationContext(),
							MainFunctions.class);
			activity.startActivity(intent);
			activity.finish();
		} else {
			Toast.makeText(activity,
					activity.getString(R.string.Toast_Connect_Failure),
					Toast.LENGTH_SHORT).show();
		}
	}

	private void handleBarcodeScan(final Bundle data) {
		String barcodeValues = data.getString(BundleUtil.BARCODE_DATA_KEY);
		String[] dataDecoded = barcodeValues.split(":");
		String secrectKey = dataDecoded[SECRECT_KEY];
		if (secrectKey.equals(ProjectUtil.md5(ProjectUtil.SECRECT_KEY))) {
			// get Server informations
			String hostname = dataDecoded[HOSTNAME];
			String ipAddress = dataDecoded[IP_ADDRESS];
			int port = Integer.parseInt(dataDecoded[PORT]);
			String password = dataDecoded[PASSWORD];
			ComputerInfos computerInfos =
					new ComputerInfos(hostname, ipAddress, port, password);
			ProjectUtil.playSound(activity, R.raw.connect);
			PhoneInfos phoneInfos =
					new PhoneInfos(password, deviceName, deviceModelNumber,
							phoneIMEI);
			network.destroyAsynTask();
			network = Network.getInstance();
			network.setHandler(this);
			network.setActivity(activity);
			network.execute(computerInfos, phoneInfos);
		} else {
			String message =
					activity.getResources().getString(
							R.string.Toast_invaild_Code);
			Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
		}
	}

	public Activity getActivity() {
		return activity;
	}

	public void setActivity(Activity activity) {
		this.activity = activity;
	}

}
